package com.jinke.api.component;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.jinke.api.common.exception.Asserts;
import com.jinke.api.security.util.AdminUserUtil;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class CustomIntegerStringConverter implements Converter<Integer> {

    @Override
    public Class supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Integer convertToJavaData(ReadCellData cellData, ExcelContentProperty excelContentProperty,
                                     GlobalConfiguration globalConfiguration) throws Exception {
        MessageHint messageHint = BeanLocator.getBean(MessageHint.class);
        CellDataTypeEnum type = cellData.getType();
        Object originalValue = null;
        switch (type) {
            case STRING:
                originalValue = cellData.getStringValue();
                break;
            case NUMBER:
                originalValue = cellData.getNumberValue();
                break;
            default:
                break;
        }
        if (originalValue == null) {
            return null; // 或者返回默认值
        }
        if (originalValue instanceof String) {
            // 这里 数字 可能会识别 type 是 字符串 捕获转换异常 处理
            try {
                return Integer.parseInt(originalValue.toString());
            } catch (NumberFormatException e) {
                // 处理无法解析的情况
                // 可以记录日志或者返回默认值
                Object[] objects = {cellData.getRowIndex()+1, cellData.getColumnIndex()+1, originalValue, messageHint.getMessage("required.type.number", null, AdminUserUtil.getUserInfo().getUserLocale())};
                Asserts.fail(messageHint.getMessage("excel.import.format.error",  objects, AdminUserUtil.getUserInfo().getUserLocale()));
            }
        } else if (originalValue instanceof Number) {
            return cellData.getNumberValue().intValue();
        }
        return cellData.getNumberValue().intValue();
    }

    @Override
    public WriteCellData<String> convertToExcelData(Integer integer, ExcelContentProperty excelContentProperty,
                                                    GlobalConfiguration globalConfiguration) throws Exception {
        return new WriteCellData<>(String.valueOf(integer));
    }
}
